package com.ficus.road.maintain.third.zh;

import com.ficus.road.maintain.util.SpringUtil;
import com.ficus.road.maintain.util.ZHTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author xiawen yang
 * @date 2022/3/16 下午1:53
 */
@Component
@Slf4j
public class BaseZH {

    // token有效期
    public static Integer expiration = 10 * 60 * 1000;
    protected Integer connectTimeout = 5000;
    protected String arg0;
    protected String arg1;
    protected String errMsg;
    protected String successMsg;
    @Value("${zhonghai.ip}")
    private String ip;
    @Value("${zhonghai.webServicePort}")
    private int webServicePort;
    @Value("${zhonghai.username}")
    private String username;
    @Value("${zhonghai.password}")
    private String password;
    @Autowired
    private SpringUtil springUtil;
    @Autowired
    private ZHTokenUtil zhTokenUtil;

    public Integer getConnectTimeout() {
        return this.connectTimeout;
    }

    public boolean printLogInfo() {
        return true;
    }

    protected String getWebserviceResponse(String url, String method, String data, String header) throws Exception {
        byte[] buf = data.getBytes();
        URL uri = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) uri.openConnection();
        httpConn.setRequestMethod(method);
        httpConn.setRequestProperty("Content-Type", "application/json");
        httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
        if (header != null && !header.equals("")) {
            httpConn.setRequestProperty("Authorization", header);
        }
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setChunkedStreamingMode(0);
        httpConn.setConnectTimeout(getConnectTimeout());
        httpConn.setReadTimeout(getConnectTimeout());
//        httpConn.connect();
        OutputStream out = httpConn.getOutputStream();
        out.write(buf);
        out.close();
        int code = httpConn.getResponseCode();
        StringBuilder sb = new StringBuilder();
        if (code == HttpURLConnection.HTTP_OK) {
            InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            sb = new StringBuilder();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
            isr.close();
        } else {
            throw new Exception("中海状态码异常, 状态码: " + code);
        }
        return sb.toString();
    }

    public String getZHData() {
        String token;
        if ("yitu".equals(username)) {
            // 生产环境
            token = zhTokenUtil.getLocalToken();
        } else {
            // 开发环境
            token = zhTokenUtil.getRemoteToken();
        }
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String authorization = getAuthorization(token);
        String host = ip + ":" + webServicePort + "/hbzs";
        String dataTemplate = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
                " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
                "<SOAP-ENV:Body>%s" +
                "</SOAP-ENV:Body>" +
                "</SOAP-ENV:Envelope>";
        String data = String.format(dataTemplate, "<m:hbzptInfo" +
                " xmlns:m=\"http://intf.webservices.bizmodules.scdp.csnt.com/\">" +
                "<arg0>" + arg0 + "</arg0>" +
                "<arg1>" + arg1 + "</arg1>" +
                "</m:hbzptInfo>");
        String rlt = null;
        try {
            rlt = getWebserviceResponse("http://" + host + "/services/BizWebService", "POST", data, authorization);
        } catch (Exception e) {
//            log.error(errMsg + ", 异常信息：{}, token时间戳: {}, token详情: {}", e.getMessage(), new Date(zhTokenUtil.getAvailToken().getLeft()), zhTokenUtil.getAvailToken().getRight());
            log.error(errMsg + ", 异常信息：{}, 超时时间配置信息：{}s", e.getMessage(), getConnectTimeout() / 1000);
            return null;
        }
        if (printLogInfo()) {
//        log.info(successMsg + ", token时间戳: {}, token详情: {}", new Date(zhTokenUtil.getAvailToken().getLeft()), zhTokenUtil.getAvailToken().getRight());
            log.info(successMsg + ", 超时时间配置信息: {}s", getConnectTimeout() / 1000);
        }
        int startIndex = rlt.indexOf("<return>") + 8;
        int endIndex = rlt.indexOf("</return>", startIndex);
//        if (startIndex + 10 >= endIndex - 3) {
//            return null;
//        }
        String res = rlt.substring(startIndex, endIndex);
        return res;
    }

    protected String getAuthorization(String token) {
        //使用base64进行加密
        byte[] tokenByte = Base64.getEncoder().encode((username + ":" + token).getBytes());
        //将加密的信息转换为string
        String tokenStr = new String(tokenByte);
        return "Basic " + tokenStr;
    }


}
